/*******************************************************************************
 * $Header$
 * $Revision$
 * $Date$
 *
 *==============================================================================
 *
 * Copyright©hxlife/hulife 
 * All rights reserved.
 * 
 * Created on 2017年9月20日
 *******************************************************************************/

package com.hualife.md.common;

import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.hualife.md.common.dao.mybatis.entity.UserApiProxy;
import com.hualife.md.common.dao.mybatis.mapper.UserApiProxyMapper;
import com.hualife.support.exception.BusinessException;
import com.hualife.support.security.AuthInterceptor;
import com.hualife.support.util.SignatureUtil;

/**
 * @description: TODO 此处填写 class 信息
 * @author 孙小冬 (mailto:sunxiaodong001@hualife.cc)
 */
public class APIAuthInterceptor extends AuthInterceptor {
	private static final Logger logger = LoggerFactory
			.getLogger(APIAuthInterceptor.class);

	@Autowired
	UserApiProxyMapper userApiProxyMapper;

	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object o) throws Exception {
		// 在调用controller具体方法前拦截
		logger.info("api权限拦截校验开始执行：");
		
		Enumeration<String> enu=request.getParameterNames();  
		while(enu.hasMoreElements()){  
		    String paraName=(String)enu.nextElement();  
		    logger.info("请求参数："+paraName+": "+request.getParameter(paraName));  
		}
		
		String appId = request.getParameter("app_id");
		String signType = request.getParameter("sign_type");
		String sign = request.getParameter("sign");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String data = request.getParameter("data");
		String page = request.getParameter("page");

		String privateKey = "";
		try {
			if (appId == null || "".equals(appId.trim())) {
				throw new BusinessException("系统ID不能为空");
			} else {
				UserApiProxy userApiProxy = userApiProxyMapper
						.selectByPrimaryKey(appId);
				if (userApiProxy == null) {
					throw new BusinessException("未找到该系统对应的密钥信息！");
				} else {
					privateKey = userApiProxy.getPrivateKey();
				}
			}

			if (signType == null || "".equals(signType.trim())) {
				signType = "md5";
			} else if (!"md5".equals(signType.trim())) {
				throw new BusinessException("不支持的加密方式！");
			}

			if (sign == null || "".equals(sign.trim())) {
				throw new BusinessException("签名不能为空！");
			}

			if (timestamp == null || "".equals(timestamp.trim())) {
				throw new BusinessException("时间戳不能为空！");
			}

			if (nonce == null || "".equals(nonce.trim())) {
				throw new BusinessException("随机数不能为空！");
			}

			Map<String, String> parameters = new HashMap<String, String>();
			parameters.put("app_id", appId);
			parameters.put("timestamp", timestamp);
			parameters.put("sign_type", signType);
			parameters.put("nonce", nonce);
			parameters.put("data", data);
			
			if (page != null) {
				parameters.put("page", page);
			}

			try {
				String signature = SignatureUtil.sign(parameters, privateKey);
				if (sign.equals(signature))
					return true;
				else
					throw new BusinessException("签名校验失败！");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				throw new BusinessException("不支持的编码格式！");
			}
		} catch (BusinessException ex) {
			String json = "{\"result_code\":\"9999\",\"result_message\":\""+ex.getMessage()+"\"}";
			response.setContentType("text/json"); 
			response.setCharacterEncoding("UTF-8");  
			response.getWriter().write(json);
			response.getWriter().flush();
			response.getWriter().close();
		}
		return false;
	}
}

/*
 * 修改历史 $Log$
 */